package demo.db.mybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(basePackages = "com.loanking.skynet.job.mysql.dao.rota", sqlSessionFactoryRef = "rotaSqlSessionFactory")
public class MyBatisConfig {

    @Bean(name = "rotaSessionFactoryBean")
    public SqlSessionFactoryBean rotaSessionFactoryBean(@Qualifier("skynetRotaDS") DataSource dataSource)
            throws IOException {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        // 配置数据库表对应的java实体类
        factory.setTypeAliasesPackage("com.loanking.skynet.job.pojo.rota");
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/loanking/skynet/job/mysql/dao/rota/mapper/*.xml");
        factory.setConfigLocation(new PathMatchingResourcePatternResolver()
                .getResource("classpath:db/mybatis/demo1/mybatis-config.xml"));
        factory.setMapperLocations(resources);


        return factory;
    }

    @Bean(name = "rotaSqlSessionFactory")
    public SqlSessionFactory rotaSqlSessionFactory(@Qualifier("rotaSessionFactoryBean") SqlSessionFactoryBean factory)
            throws Exception {
        return factory.getObject();
    }

    @Bean
    public SqlSessionTemplate rotaSqlSessionTemplate(
            @Qualifier("rotaSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier("skynetRotaDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}